package com.td.module.cooperative.service.partner;

import com.td.framework.common.pojo.PageResult;
import com.td.module.cooperative.controller.admin.partner.vo.*;
import com.td.module.cooperative.convert.partner.PartnerConvert;
import com.td.module.cooperative.dal.dataobject.partner.PartnerDO;
import com.td.module.cooperative.dal.mysql.partner.PartnerMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

import static com.td.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.td.module.cooperative.enums.ErrorCodeConstants.PARTNER_NOT_EXISTS;

/**
 * 合作伙伴 Service 实现类
 *
 * @author wangxx
 */
@Service
@Validated
public class PartnerServiceImpl implements PartnerService {

    @Resource
    private PartnerMapper partnerMapper;

    @Override
    public Long createPartner(PartnerCreateReqVO createReqVO) {
        // 插入
        PartnerDO partner = PartnerConvert.INSTANCE.convert(createReqVO);
        partnerMapper.insert(partner);
        // 返回
        return partner.getId();
    }

    @Override
    public void updatePartner(PartnerUpdateReqVO updateReqVO) {
        // 校验存在
        this.validatePartnerExists(updateReqVO.getId());
        // 更新
        PartnerDO updateObj = PartnerConvert.INSTANCE.convert(updateReqVO);
        partnerMapper.updateById(updateObj);
    }

    @Override
    public void deletePartner(Long id) {
        // 校验存在
        this.validatePartnerExists(id);
        // 删除
        partnerMapper.deleteById(id);
    }

    private void validatePartnerExists(Long id) {
        if (partnerMapper.selectById(id) == null) {
            throw exception(PARTNER_NOT_EXISTS);
        }
    }

    @Override
    public PartnerDO getPartner(Long id) {
        return partnerMapper.selectById(id);
    }

    @Override
    public List<PartnerDO> getPartnerList(Collection<Long> ids) {
        return partnerMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<PartnerDO> getPartnerPage(PartnerPageReqVO pageReqVO) {
        return partnerMapper.selectPage(pageReqVO);
    }

    @Override
    public List<PartnerDO> getPartnerList(PartnerExportReqVO exportReqVO) {
        return partnerMapper.selectList(exportReqVO);
    }

    @Override
    public List<CountPartnerRespVO> countPartnerGroupPartnerType() {
        return partnerMapper.countPartnerGroupPartnerType();
    }

}
